import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:table_calendar/table_calendar.dart';

import '../models/calendar_event.dart';
import '../providers/calendar_providers.dart';
import '../widgets/calendar_event_list.dart';
import '../widgets/calendar_type_filter.dart';
import '../widgets/add_event_dialog.dart';

/// 日历主屏幕
class CalendarScreen extends ConsumerStatefulWidget {
  /// 路由名称
  static const routeName = '/calendar';

  const CalendarScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<CalendarScreen> createState() => _CalendarScreenState();
}

class _CalendarScreenState extends ConsumerState<CalendarScreen> {
  late CalendarFormat _calendarFormat;
  late DateTime _focusedDay;
  late DateTime _selectedDay;

  @override
  void initState() {
    super.initState();
    _calendarFormat = CalendarFormat.month;
    _focusedDay = DateTime.now();
    _selectedDay = DateTime.now();
    
    // 加载示例数据（实际应用中应从存储加载）
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(calendarEventsProvider.notifier).loadSampleEvents();
    });
  }

  @override
  Widget build(BuildContext context) {
    // 获取当前选中的日期
    final selectedDate = ref.watch(selectedDateProvider);
    // 获取当前选中的事件类型过滤器
    final eventTypeFilter = ref.watch(eventTypeFilterProvider);
    // 获取当前的日历视图类型
    final calendarViewType = ref.watch(calendarViewTypeProvider);
    // 获取所有日历事件
    final allEvents = ref.watch(calendarEventsProvider);
    
    // 根据类型过滤事件
    final filteredEvents = eventTypeFilter == null
        ? allEvents
        : allEvents.where((event) => event.eventType == eventTypeFilter).toList();
    
    // 获取选中日期的事件
    final selectedDayEvents = ref
        .read(calendarEventsProvider.notifier)
        .getEventsForDay(selectedDate)
        .where((event) => eventTypeFilter == null || event.eventType == eventTypeFilter)
        .toList();

    return Scaffold(
      appBar: AppBar(
        title: const Text('家庭日历'),
        actions: [
          // 日历视图切换按钮
          IconButton(
            icon: const Icon(Icons.calendar_view_month),
            onPressed: () {
              _showViewTypeMenu(context);
            },
          ),
          // 添加事件按钮
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              _showAddEventDialog(context);
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 日历类型过滤器
          const CalendarTypeFilter(),
          
          // 根据日历视图类型显示不同的日历视图
          if (calendarViewType == CalendarViewType.month || 
              calendarViewType == CalendarViewType.week)
            _buildTableCalendar(),
          
          // 事件列表
          Expanded(
            child: CalendarEventList(
              events: selectedDayEvents,
              onEventTap: _showEventDetails,
              emptyStateMessage: '当前没有${_getEventTypeFilterName(eventTypeFilter)}事件',
            ),
          ),
        ],
      ),
    );
  }

  /// 构建表格形式的日历
  Widget _buildTableCalendar() {
    final calendarViewType = ref.watch(calendarViewTypeProvider);
    final events = ref.watch(calendarEventsProvider);
    final eventTypeFilter = ref.watch(eventTypeFilterProvider);
    
    // 创建事件映射，用于在日历上标记有事件的日期
    final eventMap = <DateTime, List<CalendarEvent>>{};
    
    for (final event in events) {
      // 如果有类型过滤器，且事件类型不匹配，则跳过
      if (eventTypeFilter != null && event.eventType != eventTypeFilter) {
        continue;
      }
      
      final eventDate = DateTime(
        event.startTime.year,
        event.startTime.month,
        event.startTime.day,
      );
      
      if (eventMap[eventDate] == null) {
        eventMap[eventDate] = [];
      }
      
      eventMap[eventDate]!.add(event);
      
      // 如果是重复事件，添加未来的重复日期
      if (event.isRecurring) {
        final now = DateTime.now();
        final endDate = DateTime(now.year + 1, 12, 31); // 展示未来一年的事件
        
        DateTime currentDate = eventDate;
        
        while (currentDate.isBefore(endDate)) {
          DateTime? nextDate;
          
          if (event.recurrenceType == 'daily') {
            nextDate = currentDate.add(const Duration(days: 1));
          } else if (event.recurrenceType == 'weekly') {
            nextDate = currentDate.add(const Duration(days: 7));
          } else if (event.recurrenceType == 'monthly') {
            // 每月同一天
            int nextMonth = currentDate.month + 1;
            int nextYear = currentDate.year;
            if (nextMonth > 12) {
              nextMonth = 1;
              nextYear++;
            }
            // 处理月底天数问题
            int day = currentDate.day;
            while (true) {
              try {
                nextDate = DateTime(nextYear, nextMonth, day);
                break;
              } catch (e) {
                day--; // 如果天数超过了下个月的最大天数，则减少一天
              }
            }
          } else if (event.recurrenceType == 'yearly') {
            // 每年同一天
            nextDate = DateTime(currentDate.year + 1, currentDate.month, currentDate.day);
          }
          
          if (nextDate != null) {
            currentDate = nextDate;
            
            if (eventMap[currentDate] == null) {
              eventMap[currentDate] = [];
            }
            eventMap[currentDate]!.add(event);
          } else {
            break;
          }
        }
      }
    }

    return TableCalendar<CalendarEvent>(
      firstDay: DateTime.utc(2020, 1, 1),
      lastDay: DateTime.utc(2030, 12, 31),
      focusedDay: _focusedDay,
      calendarFormat: calendarViewType == CalendarViewType.month
          ? CalendarFormat.month
          : CalendarFormat.week,
      selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
      eventLoader: (day) {
        final normalizedDay = DateTime(day.year, day.month, day.day);
        return eventMap[normalizedDay] ?? [];
      },
      onDaySelected: (selectedDay, focusedDay) {
        setState(() {
          _selectedDay = selectedDay;
          _focusedDay = focusedDay;
        });
        ref.read(selectedDateProvider.notifier).state = selectedDay;
      },
      onFormatChanged: (format) {
        setState(() {
          _calendarFormat = format;
        });
      },
      onPageChanged: (focusedDay) {
        setState(() {
          _focusedDay = focusedDay;
        });
      },
      calendarStyle: CalendarStyle(
        // 标记事件的样式
        markersMaxCount: 3,
        markerDecoration: BoxDecoration(
          color: eventTypeFilter?.color ?? Colors.blue,
          shape: BoxShape.circle,
        ),
        // 选中日期的样式
        selectedDecoration: const BoxDecoration(
          color: Colors.blue,
          shape: BoxShape.circle,
        ),
        todayDecoration: BoxDecoration(
          color: Colors.blue.withOpacity(0.3),
          shape: BoxShape.circle,
        ),
      ),
      headerStyle: const HeaderStyle(
        formatButtonVisible: false,
        titleCentered: true,
      ),
      locale: 'zh_CN', // 使用中文显示
    );
  }

  /// 显示日历视图类型选择菜单
  void _showViewTypeMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.calendar_view_month),
                title: const Text('月视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.month;
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.calendar_view_week),
                title: const Text('周视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.week;
                  Navigator.pop(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.view_agenda),
                title: const Text('议程视图'),
                onTap: () {
                  ref.read(calendarViewTypeProvider.notifier).state = CalendarViewType.agenda;
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示添加事件对话框
  void _showAddEventDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const AddEventDialog(),
    );
  }

  /// 显示事件详情
  void _showEventDetails(CalendarEvent event) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  CircleAvatar(
                    backgroundColor: event.eventType.color,
                    child: IconTheme(
                      data: const IconThemeData(color: Colors.white),
                      child: event.eventType.icon,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      event.title,
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.edit),
                    onPressed: () {
                      Navigator.pop(context);
                      // 显示编辑对话框
                      showDialog(
                        context: context,
                        builder: (context) => AddEventDialog(eventToEdit: event),
                      );
                    },
                  ),
                  IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () {
                      ref.read(calendarEventsProvider.notifier).removeEvent(event.id);
                      Navigator.pop(context);
                    },
                  ),
                ],
              ),
              const Divider(),
              const SizedBox(height: 8),
              Text('描述：${event.description}'),
              const SizedBox(height: 8),
              Text('开始时间：${_formatDateTime(event.startTime)}'),
              if (event.endTime != null) ...[  
                const SizedBox(height: 4),
                Text('结束时间：${_formatDateTime(event.endTime!)}'),
              ],
              if (event.location != null) ...[  
                const SizedBox(height: 4),
                Text('地点：${event.location}'),
              ],
              if (event.participants != null && event.participants!.isNotEmpty) ...[  
                const SizedBox(height: 4),
                Text('参与者：${event.participants!.join(", ")}'),
              ],
              if (event.isRecurring) ...[  
                const SizedBox(height: 4),
                Text('重复：${_getRecurrenceTypeText(event.recurrenceType)}'),
              ],
              if (event.reminderMinutes != null) ...[  
                const SizedBox(height: 4),
                Text('提醒：${_formatReminderTime(event.reminderMinutes!)}'),
              ],
              const SizedBox(height: 16),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('关闭'),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  /// 获取重复类型文本
  String _getRecurrenceTypeText(String? recurrenceType) {
    switch (recurrenceType) {
      case 'daily':
        return '每天';
      case 'weekly':
        return '每周';
      case 'monthly':
        return '每月';
      case 'yearly':
        return '每年';
      default:
        return '未知';
    }
  }

  /// 格式化提醒时间
  String _formatReminderTime(int minutes) {
    if (minutes >= 1440) { // 1天 = 1440分钟
      return '提前${minutes ~/ 1440}天';
    } else if (minutes >= 60) {
      return '提前${minutes ~/ 60}小时';
    } else {
      return '提前$minutes分钟';
    }
  }

  /// 获取事件类型过滤器名称
  String _getEventTypeFilterName(CalendarEventType? eventType) {
    if (eventType == null) {
      return '';
    }
    
    switch (eventType) {
      case CalendarEventType.birthday:
        return '生日';
      case CalendarEventType.play:
        return '游玩';
      case CalendarEventType.medical:
        return '看病';
      case CalendarEventType.anniversary:
        return '纪念日';
      case CalendarEventType.familyGathering:
        return '家庭聚会';
      case CalendarEventType.study:
        return '学习';
      case CalendarEventType.other:
        return '其他';
    }
  }
}
